import { useState, useRef, useEffect, useCallback } from 'react';

// 简单的游戏状态
interface GameState {
  score: number;
  level: number;
  lines: number;
  isPlaying: boolean;
  isPaused: boolean;
  isGameOver: boolean;
}

// 方块类型
const TETROMINOS = {
  I: { color: '#00f5ff', shape: [[1,1,1,1]] },
  O: { color: '#ffff00', shape: [[1,1],[1,1]] },
  T: { color: '#800080', shape: [[0,1,0],[1,1,1]] },
  S: { color: '#00ff00', shape: [[0,1,1],[1,1,0]] },
  Z: { color: '#ff0000', shape: [[1,1,0],[0,1,1]] },
  J: { color: '#0000ff', shape: [[1,0,0],[1,1,1]] },
  L: { color: '#ffa500', shape: [[0,0,1],[1,1,1]] }
};

// 当前方块状态
interface CurrentPiece {
  type: keyof typeof TETROMINOS;
  x: number;
  y: number;
  shape: number[][];
}

// 游戏板状态
const BOARD_WIDTH = 10;
const BOARD_HEIGHT = 20;
// 检测iOS设备的自定义hook
const useIOSDetection = () => {
  const [isIOS, setIsIOS] = useState(false);

  useEffect(() => {
    // 检测是否为iOS设备
    const ios = /iPad|iPhone|iPod/.test(navigator.userAgent);
    setIsIOS(ios);

    // 如果是iOS设备，执行更激进的优化
    if (ios) {
      const hideUrlBar = () => {
        // 多种方法隐藏URL栏
        const methods = [
          () => window.scrollTo(0, 1),
          () => window.scrollTo(0, 10),
          () => window.scrollTo(0, -1),
          () => window.scrollBy(0, -window.pageYOffset),
          () => {
            document.body.scrollTop = 1;
            document.documentElement.scrollTop = 1;
          }
        ];

        methods.forEach((method, index) => {
          setTimeout(method, index * 50);
        });

        // 最终确保隐藏
        setTimeout(() => {
          window.scrollTo(0, 1);
        }, 300);
      };

      const optimizeForIOS = () => {
        // 1. 多次尝试隐藏URL栏
        hideUrlBar();

        // 2. 设置最小高度确保触发全屏模式
        const root = document.documentElement;
        const body = document.body;

        // 设置body最小高度大于视口高度
        const minHeight = window.innerHeight + 100;
        body.style.minHeight = `${minHeight}px`;
        root.style.minHeight = `${minHeight}px`;

        // 3. 动态调整CSS变量
        const safeAreaBottom = getComputedStyle(root).getPropertyValue('--safe-area-inset-bottom').trim() || '0px';
        root.style.setProperty('--ios-safe-bottom', safeAreaBottom);
        root.style.setProperty('--ios-control-height', '160px');

        // 4. 强制设置viewport高度
        const vh = window.innerHeight * 0.01;
        root.style.setProperty('--vh', `${vh}px`);

        // 5. 监听用户交互事件隐藏URL栏
        const hideOnInteraction = () => {
          setTimeout(hideUrlBar, 100);
        };

        // 监听各种用户交互
        ['touchstart', 'touchend', 'click', 'focus'].forEach(event => {
          document.addEventListener(event, hideOnInteraction, { passive: true });
        });

        // 6. 监听resize事件（iOS Safari特殊情况）
        const handleResize = () => {
          const newVh = window.innerHeight * 0.01;
          root.style.setProperty('--vh', `${newVh}px`);

          // 再次尝试隐藏URL栏
          setTimeout(hideUrlBar, 100);
        };

        window.addEventListener('resize', handleResize);
        window.addEventListener('orientationchange', () => {
          setTimeout(() => {
            handleResize();
            hideUrlBar();
          }, 500);
        });

        // 7. 定期检查并隐藏URL栏
        const intervalId = setInterval(() => {
          if (window.pageYOffset === 0) {
            hideUrlBar();
          }
        }, 2000);

        // 8. 页面可见性变化时隐藏URL栏
        const handleVisibilityChange = () => {
          if (!document.hidden) {
            setTimeout(hideUrlBar, 500);
          }
        };

        document.addEventListener('visibilitychange', handleVisibilityChange);

        return () => {
          window.removeEventListener('resize', handleResize);
          clearInterval(intervalId);
          document.removeEventListener('visibilitychange', handleVisibilityChange);
          ['touchstart', 'touchend', 'click', 'focus'].forEach(event => {
            document.removeEventListener(event, hideOnInteraction);
          });
        };
      };

      // 页面加载完成后执行
      if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', optimizeForIOS);
      } else {
        optimizeForIOS();
      }
    }
  }, []);

  return isIOS;
};
const CELL_SIZE = 30;



function App() {
  // 检测iOS设备
  useIOSDetection(); // {{ AURA-X: Modify - 移除未使用变量 isIOS 以通过 TS 严格检查. Confirmed via 寸止 }}
  
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const mobileCanvasRef = useRef<HTMLCanvasElement>(null);
  const nextPieceCanvasRef = useRef<HTMLCanvasElement>(null);
  const nextPieceCanvasDesktopRef = useRef<HTMLCanvasElement>(null);
  const [gameState, setGameState] = useState<GameState>({
    score: 0,
    level: 0,
    lines: 0,
    isPlaying: false,
    isPaused: false,
    isGameOver: false
  });

  const [board, setBoard] = useState<number[][]>(() =>
    Array(BOARD_HEIGHT).fill(null).map(() => Array(BOARD_WIDTH).fill(0))
  );

  const [currentPiece, setCurrentPiece] = useState<CurrentPiece | null>(null);
  const [nextPiece, setNextPiece] = useState<CurrentPiece | null>(null);

  // 检测是否为移动端
  const [isMobile, setIsMobile] = useState(window.innerWidth < 1024);

  // 监听窗口大小变化
  useEffect(() => {
    const handleResize = () => {
      setIsMobile(window.innerWidth < 1024);
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // 移动端防止页面滚动
  useEffect(() => {
    if (isMobile) {
      // 防止触摸滚动，但只在游戏区域
      const preventDefault = (e: TouchEvent) => {
        // 只在游戏容器内防止默认行为
        const target = e.target as Element;
        if (target.closest('.game-container') || target.closest('.virtual-button')) {
          e.preventDefault();
        }
      };

      document.addEventListener('touchmove', preventDefault, { passive: false });

      return () => {
        document.removeEventListener('touchmove', preventDefault);
      };
    }
  }, [isMobile]);

  // 生成随机方块
  const createRandomPiece = useCallback((): CurrentPiece => {
    const types = Object.keys(TETROMINOS) as (keyof typeof TETROMINOS)[];
    const type = types[Math.floor(Math.random() * types.length)];
    return {
      type,
      x: Math.floor(BOARD_WIDTH / 2) - 1,
      y: 0,
      shape: TETROMINOS[type].shape
    };
  }, []);

  // 绘制单个格子
  const drawCell = (ctx: CanvasRenderingContext2D, x: number, y: number, color: string, cellSize: number = CELL_SIZE) => {
    const pixelX = x * cellSize;
    const pixelY = y * cellSize;

    ctx.fillStyle = color;
    ctx.fillRect(pixelX, pixelY, cellSize, cellSize);

    // 绘制边框
    ctx.strokeStyle = '#333';
    ctx.lineWidth = 1;
    ctx.strokeRect(pixelX, pixelY, cellSize, cellSize);
  };

  // 绘制下一个方块预览
  const drawNextPiece = useCallback((canvas: HTMLCanvasElement) => {
    const ctx = canvas.getContext('2d');
    if (!ctx || !nextPiece) return;

    // 清空画布
    ctx.fillStyle = '#000000';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 计算方块在预览区域的居中位置
    const shape = nextPiece.shape;
    const cellSize = Math.min(canvas.width / 6, canvas.height / 6); // 预留边距
    const shapeWidth = shape[0].length * cellSize;
    const shapeHeight = shape.length * cellSize;
    const offsetX = (canvas.width - shapeWidth) / 2;
    const offsetY = (canvas.height - shapeHeight) / 2;

    // 绘制方块
    const color = TETROMINOS[nextPiece.type].color;
    for (let y = 0; y < shape.length; y++) {
      for (let x = 0; x < shape[y].length; x++) {
        if (shape[y][x]) {
          const pixelX = offsetX + x * cellSize;
          const pixelY = offsetY + y * cellSize;

          ctx.fillStyle = color;
          ctx.fillRect(pixelX, pixelY, cellSize, cellSize);

          // 绘制边框
          ctx.strokeStyle = '#333';
          ctx.lineWidth = 1;
          ctx.strokeRect(pixelX, pixelY, cellSize, cellSize);
        }
      }
    }
  }, [nextPiece]);

  // 绘制单个Canvas
  const drawSingleBoard = useCallback((canvas: HTMLCanvasElement) => {
    const ctx = canvas.getContext('2d');
    if (!ctx) {
      console.log('❌ Canvas context is null');
      return;
    }

    // 计算cellSize - 确保游戏板正好填满Canvas
    const cellSize = Math.min(canvas.width / BOARD_WIDTH, canvas.height / BOARD_HEIGHT);
    console.log(`📐 Canvas: ${canvas.width}x${canvas.height}, cellSize: ${cellSize}, board: ${BOARD_WIDTH}x${BOARD_HEIGHT}`);

    // 清空画布
    ctx.fillStyle = '#000000';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 绘制已放置的方块
    for (let y = 0; y < BOARD_HEIGHT; y++) {
      for (let x = 0; x < BOARD_WIDTH; x++) {
        if (board[y][x]) {
          drawCell(ctx, x, y, '#666666', cellSize);
        }
      }
    }

    // 绘制当前方块
    if (currentPiece) {
      console.log('🎨 Drawing current piece:', currentPiece.type, 'at', currentPiece.x, currentPiece.y);
      const color = TETROMINOS[currentPiece.type].color;
      console.log('🎨 Piece color:', color, 'shape:', currentPiece.shape);

      for (let y = 0; y < currentPiece.shape.length; y++) {
        for (let x = 0; x < currentPiece.shape[y].length; x++) {
          if (currentPiece.shape[y][x]) {
            const boardX = currentPiece.x + x;
            const boardY = currentPiece.y + y;
            console.log(`🎨 Drawing cell at board position: ${boardX}, ${boardY}`);

            if (boardX >= 0 && boardX < BOARD_WIDTH && boardY >= 0 && boardY < BOARD_HEIGHT) {
              drawCell(ctx, boardX, boardY, color, cellSize);
            }
          }
        }
      }
    } else {
      console.log('⚠️ No current piece to draw');
    }

    // 绘制网格线
    ctx.strokeStyle = '#333333';
    ctx.lineWidth = 1;

    // 垂直线
    for (let x = 0; x <= BOARD_WIDTH; x++) {
      ctx.beginPath();
      ctx.moveTo(x * cellSize, 0);
      ctx.lineTo(x * cellSize, BOARD_HEIGHT * cellSize);
      ctx.stroke();
    }

    // 水平线
    for (let y = 0; y <= BOARD_HEIGHT; y++) {
      ctx.beginPath();
      ctx.moveTo(0, y * cellSize);
      ctx.lineTo(BOARD_WIDTH * cellSize, y * cellSize);
      ctx.stroke();
    }

    console.log('✅ Canvas绘制完成');
  }, [board, currentPiece]);

  // 绘制游戏板 - 同时绘制桌面端和移动端Canvas
  const drawBoard = useCallback(() => {
    const desktopCanvas = canvasRef.current;
    const mobileCanvas = mobileCanvasRef.current;

    console.log(`📱 isMobile: ${isMobile}, window.innerWidth: ${window.innerWidth}`);

    if (desktopCanvas) {
      console.log('🖥️ Drawing desktop canvas');
      drawSingleBoard(desktopCanvas);
    }

    if (mobileCanvas) {
      console.log('📱 Drawing mobile canvas');
      drawSingleBoard(mobileCanvas);
    }

    if (!desktopCanvas && !mobileCanvas) {
      console.log('❌ Both canvas refs are null');
    }
  }, [drawSingleBoard, isMobile]);

  // 开始游戏
  const startGame = () => {
    console.log('🎮 Starting game...');
    setGameState(prev => ({
      ...prev,
      isPlaying: true,
      isPaused: false,
      isGameOver: false,
      score: 0,
      level: 0,
      lines: 0
    }));
    const newPiece = createRandomPiece();
    const newNextPiece = createRandomPiece();
    console.log('🎯 Created new piece:', newPiece);
    console.log('🔮 Created next piece:', newNextPiece);
    setCurrentPiece(newPiece);
    setNextPiece(newNextPiece);
    setBoard(Array(BOARD_HEIGHT).fill(null).map(() => Array(BOARD_WIDTH).fill(0)));
    console.log('✅ Game started successfully');
  };

  // 暂停游戏
  const togglePause = () => {
    setGameState(prev => ({
      ...prev,
      isPaused: !prev.isPaused
    }));
  };

  // 重置游戏
  const resetGame = () => {
    setGameState({
      score: 0,
      level: 0,
      lines: 0,
      isPlaying: false,
      isPaused: false,
      isGameOver: false
    });
    setCurrentPiece(null);
    setNextPiece(null);
    setBoard(Array(BOARD_HEIGHT).fill(null).map(() => Array(BOARD_WIDTH).fill(0)));
  };

  // 检查碰撞
  const checkCollision = useCallback((piece: CurrentPiece, deltaX = 0, deltaY = 0): boolean => {
    for (let y = 0; y < piece.shape.length; y++) {
      for (let x = 0; x < piece.shape[y].length; x++) {
        if (piece.shape[y][x]) {
          const newX = piece.x + x + deltaX;
          const newY = piece.y + y + deltaY;

          if (newX < 0 || newX >= BOARD_WIDTH || newY >= BOARD_HEIGHT) {
            return true;
          }

          if (newY >= 0 && board[newY][newX]) {
            return true;
          }
        }
      }
    }
    return false;
  }, [board]);

  // 旋转方块
  const rotatePiece = useCallback(() => {
    if (!currentPiece || !gameState.isPlaying || gameState.isPaused) return;

    // 简单的90度顺时针旋转
    const rotatedShape = currentPiece.shape[0].map((_, index) =>
      currentPiece.shape.map(row => row[index]).reverse()
    );

    const rotatedPiece = {
      ...currentPiece,
      shape: rotatedShape
    };

    // 检查旋转后是否有碰撞
    if (!checkCollision(rotatedPiece, 0, 0)) {
      setCurrentPiece(rotatedPiece);
    }
  }, [currentPiece, gameState.isPlaying, gameState.isPaused, checkCollision]);

  // 移动方块
  const movePiece = useCallback((deltaX: number, deltaY: number) => {
    if (!currentPiece || !gameState.isPlaying || gameState.isPaused) return;

    if (!checkCollision(currentPiece, deltaX, deltaY)) {
      setCurrentPiece(prev => prev ? {
        ...prev,
        x: prev.x + deltaX,
        y: prev.y + deltaY
      } : null);
    } else if (deltaY > 0) {
      // 方块落地，固定到游戏板
      const newBoard = [...board];
      for (let y = 0; y < currentPiece.shape.length; y++) {
        for (let x = 0; x < currentPiece.shape[y].length; x++) {
          if (currentPiece.shape[y][x]) {
            const boardY = currentPiece.y + y;
            const boardX = currentPiece.x + x;
            if (boardY >= 0) {
              newBoard[boardY][boardX] = 1;
            }
          }
        }
      }

      // 检查并清除满行
      let linesCleared = 0;
      for (let y = BOARD_HEIGHT - 1; y >= 0; y--) {
        if (newBoard[y].every(cell => cell !== 0)) {
          newBoard.splice(y, 1);
          newBoard.unshift(Array(BOARD_WIDTH).fill(0));
          linesCleared++;
          y++; // 重新检查当前行
        }
      }

      // 更新分数和统计
      if (linesCleared > 0) {
        const points = [0, 100, 300, 500, 800][linesCleared] || 0;
        setGameState(prev => ({
          ...prev,
          score: prev.score + points * (prev.level + 1),
          lines: prev.lines + linesCleared,
          level: Math.floor((prev.lines + linesCleared) / 10)
        }));
      }

      setBoard(newBoard);

      // 使用下一个方块作为新的当前方块，并生成新的下一个方块
      if (nextPiece && !checkCollision(nextPiece, 0, 0)) {
        setCurrentPiece(nextPiece);
        setNextPiece(createRandomPiece());
      } else {
        // 游戏结束
        setGameState(prev => ({
          ...prev,
          isPlaying: false,
          isPaused: false,
          isGameOver: true
        }));
        setCurrentPiece(null);
        setNextPiece(null);
      }
    }
  }, [currentPiece, nextPiece, gameState.isPlaying, gameState.isPaused, board, checkCollision, createRandomPiece]);

  // 键盘控制
  useEffect(() => {
    const handleKeyPress = (e: KeyboardEvent) => {
      if (!gameState.isPlaying) return;

      switch (e.key) {
        case 'ArrowLeft':
          e.preventDefault();
          movePiece(-1, 0);
          break;
        case 'ArrowRight':
          e.preventDefault();
          movePiece(1, 0);
          break;
        case 'ArrowDown':
          e.preventDefault();
          movePiece(0, 1);
          break;
        case 'ArrowUp':
          e.preventDefault();
          rotatePiece();
          break;
        case ' ':
          e.preventDefault();
          // 硬降
          if (currentPiece) {
            let dropY = 0;
            while (!checkCollision(currentPiece, 0, dropY + 1)) {
              dropY++;
            }
            movePiece(0, dropY);
          }
          break;
        case 'Escape':
          e.preventDefault();
          togglePause();
          break;
      }
    };

    window.addEventListener('keydown', handleKeyPress);
    return () => window.removeEventListener('keydown', handleKeyPress);
  }, [currentPiece, gameState.isPlaying, gameState.isPaused]);

  // 游戏循环
  useEffect(() => {
    if (!gameState.isPlaying || gameState.isPaused) return;

    // 根据等级调整下落速度
    const dropSpeed = Math.max(100, 1000 - gameState.level * 100);

    const interval = setInterval(() => {
      movePiece(0, 1);
    }, dropSpeed);

    return () => clearInterval(interval);
  }, [movePiece, gameState.isPlaying, gameState.isPaused, gameState.level]);

  // 重新绘制游戏板
  useEffect(() => {
    drawBoard();
  }, [drawBoard]);

  // Canvas初始化
  useEffect(() => {
    drawBoard();
  }, [drawBoard]);

  // 绘制下一个方块预览
  useEffect(() => {
    const mobileCanvas = nextPieceCanvasRef.current;
    const desktopCanvas = nextPieceCanvasDesktopRef.current;

    if (mobileCanvas) {
      drawNextPiece(mobileCanvas);
    }
    if (desktopCanvas) {
      drawNextPiece(desktopCanvas);
    }
  }, [drawNextPiece]);

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-900 via-black to-gray-900 text-white overflow-hidden">
      {/* 移动端布局 */}
      <div className="lg:hidden">
        {/* 顶部信息栏 - 移动端紧凑设计 */}
        <div className="bg-gray-800/90 backdrop-blur-sm border-b border-gray-700 px-4 py-2">
          <div className="flex items-center justify-between">
            <h1 className="text-lg font-bold bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent">
              🎮 俄罗斯方块
            </h1>
            <div className="flex items-center gap-4 text-sm">
              <div className="text-yellow-400 font-bold">{gameState.score.toLocaleString()}</div>
              <div className="text-blue-400">Lv.{gameState.level}</div>
              <div className="text-green-400">{gameState.lines}行</div>
            </div>
          </div>
        </div>

        {/* 主游戏区域 - 移动端上下布局 */}
        <div className="game-container flex flex-col" style={{
          height: 'calc(100dvh - 80px)',
          paddingBottom: 'env(safe-area-inset-bottom, 0px)',
          position: 'relative'
        }}>
          {/* 上方：游戏板区域 */}
          <div className="flex-1 flex items-center justify-center p-1 min-h-0" style={{
            paddingBottom: 'calc(env(safe-area-inset-bottom, 0px) * 0.5)',
            marginBottom: '0px'
          }}>
            <div className="relative" style={{
              marginBottom: 'calc(env(safe-area-inset-bottom, 0px) * 0.3)',
              position: 'relative'
            }}>
              <canvas
                ref={mobileCanvasRef}
                width={300}
                height={600}
                className="border-4 border-red-500 rounded-lg shadow-2xl"
                style={{
                  width: '300px',
                  height: '600px',
                  maxWidth: '70vw',
                  maxHeight: 'calc(65vh - env(safe-area-inset-bottom, 0px))',
                  minHeight: '350px',
                  imageRendering: 'pixelated',
                  display: 'block',
                  backgroundColor: '#000000',
                  zIndex: 10,
                  position: 'relative'
                }}
              />

              {/* 游戏状态覆盖层 */}
              {gameState.isPaused && (
                <div className="absolute inset-0 bg-black/80 flex items-center justify-center rounded-lg">
                  <div className="text-center">
                    <div className="text-xl font-bold mb-2">⏸️ 暂停</div>
                    <div className="text-xs text-gray-300">点击继续</div>
                  </div>
                </div>
              )}

              {!gameState.isPlaying && !gameState.isGameOver && (
                <div className="absolute inset-0 bg-black/80 flex items-center justify-center rounded-lg">
                  <div className="text-center">
                    <div className="text-xl font-bold mb-2">🎯 开始</div>
                    <div className="text-xs text-gray-300">点击开始按钮</div>
                  </div>
                </div>
              )}

              {gameState.isGameOver && (
                <div className="absolute inset-0 bg-black/80 flex items-center justify-center rounded-lg">
                  <div className="text-center">
                    <div className="text-xl font-bold mb-2">🎮 游戏结束</div>
                    <div className="text-xs text-gray-300">点击重新开始</div>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* 下方：控制区域 */}
          <div className="flex-shrink-0 p-3 bg-gray-800/90 backdrop-blur-sm border-t border-gray-600" style={{
            paddingBottom: 'max(40px, env(safe-area-inset-bottom, 0px))',
            marginBottom: 'env(safe-area-inset-bottom, 0px)',
            minHeight: '140px',
            position: 'relative',
            zIndex: 1000,
            background: 'linear-gradient(to bottom, rgba(31, 41, 55, 0.95), rgba(17, 24, 39, 0.98))',
            borderTop: '2px solid rgba(75, 85, 99, 0.8)'
          }}>
            <div className="flex items-center justify-between max-w-sm mx-auto">
              {/* 左侧：下一个方块预览和游戏控制 */}
              <div className="flex items-center gap-3">
                {/* 下一个方块预览 */}
                <div className="bg-gray-800/70 backdrop-blur-sm p-2 rounded-lg border border-gray-600">
                  <div className="text-xs text-gray-300 mb-1 text-center">下一个</div>
                  <div className="flex justify-center">
                    <canvas
                      ref={nextPieceCanvasRef}
                      width={60}
                      height={60}
                      className="border border-gray-600 bg-gray-900 rounded"
                    />
                  </div>
                </div>

                {/* 游戏控制按钮 */}
                <div className="flex gap-2">
                  {!gameState.isPlaying ? (
                    <button
                      className="px-3 py-2 bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white text-sm font-bold rounded-lg transition-all duration-200 shadow-lg"
                      onClick={startGame}
                    >
                      🚀 开始
                    </button>
                  ) : (
                    <>
                      <button
                        className="px-3 py-2 bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white text-sm font-bold rounded-lg transition-all duration-200 shadow-lg"
                        onClick={togglePause}
                      >
                        {gameState.isPaused ? '▶️' : '⏸️'}
                      </button>
                      <button
                        className="px-3 py-2 bg-gradient-to-r from-red-500 to-red-600 hover:from-red-600 hover:to-red-700 text-white text-sm font-bold rounded-lg transition-all duration-200 shadow-lg"
                        onClick={resetGame}
                      >
                        🔄
                      </button>
                    </>
                  )}
                </div>
              </div>

              {/* 右侧：虚拟按键区域 */}
              <div className="flex items-center gap-2">
                {/* 旋转按钮 */}
                <button
                  className="virtual-button w-12 h-12 bg-purple-600/80 hover:bg-purple-600 active:bg-purple-700 rounded-lg text-white font-bold text-lg transition-all duration-150 shadow-lg border border-purple-500"
                  onTouchStart={(e) => {
                    e.preventDefault();
                    rotatePiece();
                  }}
                  onClick={(e) => {
                    e.preventDefault();
                    rotatePiece();
                  }}
                >
                  ↻
                </button>

                {/* 方向控制 */}
                <div className="grid grid-cols-3 gap-1">
                  <button
                    className="virtual-button w-10 h-10 bg-gray-700/80 hover:bg-gray-600 active:bg-gray-500 rounded text-white font-bold text-sm transition-all duration-150 shadow border border-gray-600"
                    onTouchStart={(e) => {
                      e.preventDefault();
                      movePiece(-1, 0);
                    }}
                    onClick={(e) => {
                      e.preventDefault();
                      movePiece(-1, 0);
                    }}
                  >
                    ←
                  </button>
                  <button
                    className="virtual-button w-10 h-10 bg-gray-700/80 hover:bg-gray-600 active:bg-gray-500 rounded text-white font-bold text-sm transition-all duration-150 shadow border border-gray-600"
                    onTouchStart={(e) => {
                      e.preventDefault();
                      movePiece(0, 1);
                    }}
                    onClick={(e) => {
                      e.preventDefault();
                      movePiece(0, 1);
                    }}
                  >
                    ↓
                  </button>
                  <button
                    className="virtual-button w-10 h-10 bg-gray-700/80 hover:bg-gray-600 active:bg-gray-500 rounded text-white font-bold text-sm transition-all duration-150 shadow border border-gray-600"
                    onTouchStart={(e) => {
                      e.preventDefault();
                      movePiece(1, 0);
                    }}
                    onClick={(e) => {
                      e.preventDefault();
                      movePiece(1, 0);
                    }}
                  >
                    →
                  </button>
                </div>

                {/* 硬降按钮 */}
                <button
                  className="virtual-button w-14 h-12 bg-orange-600/80 hover:bg-orange-600 active:bg-orange-700 rounded-lg text-white font-bold text-sm transition-all duration-150 shadow-lg border border-orange-500"
                  onTouchStart={(e) => {
                    e.preventDefault();
                    if (currentPiece) {
                      let dropY = 0;
                      while (!checkCollision(currentPiece, 0, dropY + 1)) {
                        dropY++;
                      }
                      movePiece(0, dropY);
                    }
                  }}
                  onClick={(e) => {
                    e.preventDefault();
                    if (currentPiece) {
                      let dropY = 0;
                      while (!checkCollision(currentPiece, 0, dropY + 1)) {
                        dropY++;
                      }
                      movePiece(0, dropY);
                    }
                  }}
                >
                  ⬇
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 桌面端布局 */}
      <div className="hidden lg:block">
        {/* 标题栏 */}
        <div className="bg-gray-800/50 backdrop-blur-sm border-b border-gray-700">
          <div className="container mx-auto px-4 py-4">
            <h1 className="text-2xl md:text-3xl font-bold text-center bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent">
              🎮 俄罗斯方块
            </h1>
          </div>
        </div>

        {/* 主游戏区域 */}
        <div className="container mx-auto px-4 py-6">
          <div className="flex flex-row gap-6 justify-center items-start">

            {/* 游戏板区域 */}
            <div className="flex flex-col items-center">
              <div className="relative">
                <canvas
                  ref={canvasRef}
                  width={300}
                  height={600}
                  className="border-4 border-red-500 bg-gray-800 rounded-lg shadow-2xl"
                  style={{
                    imageRendering: 'pixelated',
                    display: 'block'
                  }}
                />

                {/* 游戏状态覆盖层 */}
                {gameState.isPaused && (
                  <div className="absolute inset-0 bg-black/80 flex items-center justify-center rounded-lg">
                    <div className="text-center">
                      <div className="text-2xl font-bold mb-2">⏸️ 暂停游戏</div>
                      <div className="text-sm text-gray-300">点击继续恢复游戏</div>
                    </div>
                  </div>
                )}

                {!gameState.isPlaying && !gameState.isGameOver && (
                  <div className="absolute inset-0 bg-black/80 flex items-center justify-center rounded-lg">
                    <div className="text-center">
                      <div className="text-2xl font-bold mb-4">🎯 准备开始</div>
                      <div className="text-sm text-gray-300">点击开始游戏按钮</div>
                    </div>
                  </div>
                )}

                {gameState.isGameOver && (
                  <div className="absolute inset-0 bg-black/80 flex items-center justify-center rounded-lg">
                    <div className="text-center">
                      <div className="text-2xl font-bold mb-4">🎮 游戏结束</div>
                      <div className="text-sm text-gray-300">点击重新开始按钮</div>
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* 侧边栏 */}
            <div className="flex flex-col gap-4 w-full lg:w-64">

            {/* 下一个方块预览 */}
            <div className="bg-gray-800/70 backdrop-blur-sm p-4 rounded-xl border border-gray-600 shadow-lg">
              <h3 className="text-sm font-bold mb-3 text-gray-300">🔮 下一个方块</h3>
              <div className="flex justify-center">
                <canvas
                  ref={nextPieceCanvasDesktopRef}
                  width={80}
                  height={80}
                  className="border border-gray-600 bg-gray-900 rounded-lg"
                />
              </div>
            </div>

            {/* 游戏统计 */}
            <div className="bg-gray-800/70 backdrop-blur-sm p-4 rounded-xl border border-gray-600 shadow-lg">
              <h3 className="text-sm font-bold mb-3 text-gray-300">📊 游戏统计</h3>
              <div className="space-y-3">
                <div className="flex justify-between items-center">
                  <span className="text-gray-400">分数</span>
                  <span className="text-xl font-bold text-yellow-400">{gameState.score.toLocaleString()}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-400">等级</span>
                  <span className="text-lg font-bold text-blue-400">{gameState.level}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-400">行数</span>
                  <span className="text-lg font-bold text-green-400">{gameState.lines}</span>
                </div>
              </div>
            </div>

            {/* 游戏控制 */}
            <div className="bg-gray-800/70 backdrop-blur-sm p-4 rounded-xl border border-gray-600 shadow-lg">
              <h3 className="text-sm font-bold mb-3 text-gray-300">🎮 游戏控制</h3>

              {!gameState.isPlaying ? (
                <button
                  className="w-full px-4 py-3 bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white font-bold rounded-lg transition-all duration-200 transform hover:scale-105 shadow-lg"
                  onClick={startGame}
                >
                  🚀 开始游戏
                </button>
              ) : (
                <div className="space-y-2">
                  <button
                    className="w-full px-4 py-3 bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white font-bold rounded-lg transition-all duration-200 transform hover:scale-105 shadow-lg"
                    onClick={togglePause}
                  >
                    {gameState.isPaused ? '▶️ 继续' : '⏸️ 暂停'}
                  </button>
                  <button
                    className="w-full px-4 py-3 bg-gradient-to-r from-red-500 to-red-600 hover:from-red-600 hover:to-red-700 text-white font-bold rounded-lg transition-all duration-200 transform hover:scale-105 shadow-lg"
                    onClick={resetGame}
                  >
                    🔄 重新开始
                  </button>
                </div>
              )}
            </div>

            {/* 桌面端控制说明 */}
            <div className="bg-gray-800/70 backdrop-blur-sm p-4 rounded-xl border border-gray-600 shadow-lg">
              <h3 className="text-sm font-bold mb-3 text-gray-300">⌨️ 键盘控制</h3>
              <div className="space-y-2 text-xs">
                <div className="flex items-center gap-2">
                  <span className="bg-gray-700 px-2 py-1 rounded text-xs">←→</span>
                  <span className="text-gray-400">左右移动</span>
                </div>
                <div className="flex items-center gap-2">
                  <span className="bg-gray-700 px-2 py-1 rounded text-xs">↓</span>
                  <span className="text-gray-400">软降</span>
                </div>
                <div className="flex items-center gap-2">
                  <span className="bg-gray-700 px-2 py-1 rounded text-xs">↑</span>
                  <span className="text-gray-400">旋转</span>
                </div>
                <div className="flex items-center gap-2">
                  <span className="bg-gray-700 px-2 py-1 rounded text-xs">空格</span>
                  <span className="text-gray-400">硬降</span>
                </div>
              </div>
            </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default App;
